package com.jnu.chengzhi.service;

import com.jnu.chengzhi.dao.UserDao;
import com.jnu.chengzhi.entity.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Program: ChengZhi
 * DATE: 2022/3/26
 * Author: 周洁锋
 * Description:
 */

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        MyUser myUser = userDao.findByName(s);
        if (myUser == null)   throw new UsernameNotFoundException("Fail to find " + s);
        authorityList.add(new SimpleGrantedAuthority(myUser.getRole()));
        User user = new User(s, "{noop}" + myUser.getPassword(), authorityList);
        return user;
    }
}
